package com.scs.application.modules.msg.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.scs.application.core.aliyun.sms.handler.AliyunSmsHandler;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.msg.domain.RawMessage;
import com.scs.application.core.msg.domain.SmsMessage;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.msg.entity.PushedRecord;
import com.scs.application.modules.msg.exception.SendMessageException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Description: 短信消息
 */
@Component
@AllArgsConstructor
@Slf4j
public class SendSmsMessageProvider implements SendMessageProvider<SmsMessage> {

    private final AliyunSmsHandler aliyunSmsHandler;

    @Override
    public boolean check(SmsMessage message) {
        if (StringUtils.isBlank(message.getMobile())) {
            throw new BusinessException("短信消息校验失败，手机号不能为空");
        }
        if (StringUtils.isBlank(message.getTemplateCode())) {
            throw new BusinessException("短信消息校验失败，模板ID不能为空");
        }
        return true;
    }

    @Override
    public boolean support(Class<? extends RawMessage> clz) {
        return (SmsMessage.class.isAssignableFrom(clz));
    }

    /**
     * 构建pushRecord
     *
     * @param pushedRecord
     * @param smsMessage
     * @return
     */
    @Override
    public PushedRecord getPushedRecord(PushedRecord pushedRecord, SmsMessage smsMessage) {
        pushedRecord.setTitle(null)
                .setContent(smsMessage.getTemplateCode())
                .setReceiver(smsMessage.getMobile())
                .setParams(smsMessage.getParams() != null ? JSONObject.parseObject(JSON.toJSONString(smsMessage.getParams())) : null);
        return pushedRecord;
    }

    @Override
    public void send(SmsMessage smsMessage) throws SendMessageException {

        boolean sendSms = aliyunSmsHandler.sendSms(smsMessage.getMobile(), smsMessage.getTemplateCode(), smsMessage.getParams());
        if (!sendSms) {
            throw new SendMessageException("短信发送失败");
        }
        log.info("短信发送{}，接收手机号：{}，模板编号：{}，参数：{}", sendSms ? "成功" : "失败",
                smsMessage.getMobile(), smsMessage.getTemplateCode(), smsMessage.getParams());

    }
}
